package com.sxjh.common;

import cn.hutool.core.util.RandomUtil;

import java.util.Date;

/**
 * 送检随机码
 * @author zixin
 * @since 2021-05-28
 */
public class InspectRandom {

  private final static Long time = 1622183436L;
  private final static String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
  private final static int scale = 36;
  private final static Integer[] tc = {1,2,3,4,5,6,7,8,9};

  // 转成36进制
  public static String createId(long num) {
    StringBuilder sb = new StringBuilder();
    int remainder = 0;
    while (num > scale - 1) {
      /**
       * 对 scale 进行求余，然后将余数追加至 sb 中，由于是从末位开始追加的，因此最后需要反转（reverse）字符串
       */
      remainder = Long.valueOf(num % scale).intValue();
      sb.append(chars.charAt(remainder));
      num = num / scale;
    }
    sb.append(chars.charAt(Long.valueOf(num).intValue()));
    String value = sb.reverse().toString();
    return value;
  }

  // 生成唯一的6位数的 id
  public static String idAt5() {
    synchronized (InspectRandom.class) {
      // 暂定1.1秒确保精确到秒的时间戳唯一
      try {
        Thread.sleep(1100);
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
      // 计算当前时间与指定时间的时间戳，并进行36进制转码
      Long dayTime = new Date().getTime();
      Long diff = (dayTime / 1000) - time;
      String name = createId(diff);
      int count = name.length();
      if (count < 6) {
        int size = 6 - count;
        for (int i = 0; i < size; i++) {
          name += RandomUtil.randomEle(tc);
        }
      }
      return name;
    }
  }

}
